package com.jiancong.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jiancong.domain.ResponseResult;
import com.jiancong.domain.dto.UserDetailDto;
import com.jiancong.domain.dto.UserQueryCriteria;
import com.jiancong.domain.dto.UserUpdateDto;
import com.jiancong.domain.entity.LoginUser;
import com.jiancong.domain.entity.Role;
import com.jiancong.domain.entity.User;
import com.jiancong.domain.entity.UserRole;
import com.jiancong.domain.vo.PageVo;
import com.jiancong.domain.vo.UserInfoVo;
import com.jiancong.domain.vo.UserVo;
import com.jiancong.enums.AppHttpCodeEnum;
import com.jiancong.exception.SystemException;
import com.jiancong.mapper.RoleMapper;
import com.jiancong.mapper.RoleMenuMapper;
import com.jiancong.mapper.UserMapper;
import com.jiancong.service.UserService;
import com.jiancong.utils.BeanCopyUtils;
import com.jiancong.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户表(User)表服务实现类
 *
 * @author makejava
 * @since 2022-02-09 00:28:30
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;
    @Override
    public ResponseResult userInfo() {
        //获取当前用户id
        Long userId = SecurityUtils.getUserId();
        //根据用户id查询用户信息
        User user = userMapper.getById(userId);
        //封装成UserInfoVo
        UserInfoVo vo = BeanCopyUtils.copyBean(user,UserInfoVo.class);
        return ResponseResult.okResult(vo);
    }

    @Override
    @Transactional
    public ResponseResult updateUserInfo(User user) {
        userMapper.updateById(user);
        return ResponseResult.okResult();
    }

    @Override
    @Transactional
    public ResponseResult register(User user) {

        //对数据进行非空判断
        if(!StringUtils.hasText(user.getUserName())){
            throw new SystemException(AppHttpCodeEnum.USERNAME_NOT_NULL);
        }
        if(!StringUtils.hasText(user.getPassword())){
            throw new SystemException(AppHttpCodeEnum.PASSWORD_NOT_NULL);
        }
        if(!StringUtils.hasText(user.getEmail())){
            throw new SystemException(AppHttpCodeEnum.EMAIL_NOT_NULL);
        }
        if(!StringUtils.hasText(user.getNickName())){
            throw new SystemException(AppHttpCodeEnum.NICKNAME_NOT_NULL);
        }
        //对数据进行是否存在的判断
        if(userNameExist(user.getUserName())){
            throw new SystemException(AppHttpCodeEnum.USERNAME_EXIST);
        }
        if(nickNameExist(user.getNickName())){
            throw new SystemException(AppHttpCodeEnum.NICKNAME_EXIST);
        }
        if(userEmailExist(user.getEmail())){
            throw new SystemException(AppHttpCodeEnum.NICKNAME_EXIST);
        }
        //对密码进行加密
        String encodePassword = passwordEncoder.encode(user.getPassword());
        user.setPassword(encodePassword);
        // 设置默认角色为普通用户
        user.setType("0"); // 0 表示普通用户
        user.setIsAuthor('0'); // 默认没有发布文章的权限
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        userMapper.save(user);
        // 2. 获取生成的主键 id
        Long userId = user.getId();
        // 3. 将用户与默认角色关联
        userMapper.insertUserRole(userId, 2L); // 2 是普通角色的 role_id
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult getUserPageList(UserQueryCriteria criteria) {
        PageHelper.startPage(criteria.getPageNum(), criteria.getPageSize());
        List<User> users = userMapper.selectUsersByCriteria(criteria);
        PageInfo<User> pageInfo = new PageInfo<>(users);
        PageVo pageVo = new PageVo(users, pageInfo.getTotal());

        return ResponseResult.okResult(pageVo);
    }

    @Autowired
    private RoleMapper roleMapper;

    @Transactional
    public boolean createUser(User user) {
        //对数据进行非空判断
        if(!StringUtils.hasText(user.getUserName())){
            throw new SystemException(AppHttpCodeEnum.USERNAME_NOT_NULL);
        }
        if(!StringUtils.hasText(user.getPassword())){
            throw new SystemException(AppHttpCodeEnum.PASSWORD_NOT_NULL);
        }
        if(!StringUtils.hasText(user.getEmail())){
            throw new SystemException(AppHttpCodeEnum.EMAIL_NOT_NULL);
        }
        if(!StringUtils.hasText(user.getNickName())){
            throw new SystemException(AppHttpCodeEnum.NICKNAME_NOT_NULL);
        }
        //对数据进行是否存在的判断
        if(userNameExist(user.getUserName())){
            throw new SystemException(AppHttpCodeEnum.USERNAME_EXIST);
        }
        if(nickNameExist(user.getNickName())){
            throw new SystemException(AppHttpCodeEnum.NICKNAME_EXIST);
        }
        if(userEmailExist(user.getEmail())){
            throw new SystemException(AppHttpCodeEnum.EMAIL_EXIST);
        }
        // 密码加密
        String encryptedPassword = passwordEncoder.encode(user.getPassword());

        user.setPassword(encryptedPassword);
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        // 插入用户记录
        int result = userMapper.insertUser(user);
        if (result > 0) {
            // 插入用户角色关联
            for (Long roleId : user.getRoleIds()) {
                UserRole userRole = new UserRole();
                userRole.setUserId(user.getId());
                userRole.setRoleId(roleId);
                roleMapper.insertUserRole(userRole);
            }
            return true;
        }
        return false;
    }

    @Override
    @Transactional
    public boolean deleteUser(Long id) {
        // 执行删除操作，这里使用逻辑删除作为示例
        int result = userMapper.updateUserStatus(id, "1"); // 假设状态 "1" 表示已删除
        return result > 0;
    }

    @Override
    public UserDetailDto getUserDetail(Long id) {
        User user = userMapper.selectUserById(id);
        if (user != null) {
            List<String> roleIds = roleMapper.selectRoleIdsByUserId(id);
            List<Role> roles = roleMapper.listAllRoles();
            UserDetailDto response = new UserDetailDto();
            response.setRoleIds(roleIds);
            response.setRoles(roles);
            response.setUser(user);
            return response;
        }
        return null;
    }

    @Override
    @Transactional
    public boolean updateUser(UserUpdateDto userUpdateDto) {
        // 更新用户信息
        User user = BeanCopyUtils.copyBean(userUpdateDto, User.class);
        user.setUpdateTime(new Date());
        Long userId = SecurityUtils.getUserId();
        user.setUpdateBy(userId);
        int result = userMapper.updateUser(user);
        if (result > 0) {
            // 删除旧的用户角色关联
            roleMapper.deleteUserRolesByUserId(userUpdateDto.getId());
            // 插入新的用户角色关联
            for (Long roleId : userUpdateDto.getRoleIds()) {
                UserRole userRole = new UserRole();
                userRole.setUserId(userUpdateDto.getId());
                userRole.setRoleId(roleId);
                roleMapper.insertUserRole(userRole);
            }
            return true;
        }
        return false;
    }



    private boolean nickNameExist(String nickName) {
        List<User> userList = userMapper.selectByNickName(nickName);
        int size = userList.size();
        return size > 0;
    }

    private boolean userNameExist(String userName) {
        List<User> userList = userMapper.selectByUserName(userName);
        int size = userList.size();
        return size > 0;
    }
    private boolean userEmailExist(String userEmail) {
        List<User> userList = userMapper.selectByUserEmail(userEmail);
        int size = userList.size();
        return size > 0;
    }

//
//    @Autowired
//    private PasswordEncoder passwordEncoder;
//    @Override
//    public ResponseResult register(User user) {
//        //对数据进行非空判断
//        if(!StringUtils.hasText(user.getUserName())){
//            throw new SystemException(AppHttpCodeEnum.USERNAME_NOT_NULL);
//        }
//        if(!StringUtils.hasText(user.getPassword())){
//            throw new SystemException(AppHttpCodeEnum.PASSWORD_NOT_NULL);
//        }
//        if(!StringUtils.hasText(user.getEmail())){
//            throw new SystemException(AppHttpCodeEnum.EMAIL_NOT_NULL);
//        }
//        if(!StringUtils.hasText(user.getNickName())){
//            throw new SystemException(AppHttpCodeEnum.NICKNAME_NOT_NULL);
//        }
//        //对数据进行是否存在的判断
//        if(userNameExist(user.getUserName())){
//            throw new SystemException(AppHttpCodeEnum.USERNAME_EXIST);
//        }
//        if(nickNameExist(user.getNickName())){
//            throw new SystemException(AppHttpCodeEnum.NICKNAME_EXIST);
//        }
//        //...
//        //对密码进行加密
//        String encodePassword = passwordEncoder.encode(user.getPassword());
//        user.setPassword(encodePassword);
//        //存入数据库
//        save(user);
//        return ResponseResult.okResult();
//    }
//
//    @Override
//    public ResponseResult selectUserPage(User user, Integer pageNum, Integer pageSize) {
//        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper();
//
//        queryWrapper.like(StringUtils.hasText(user.getUserName()),User::getUserName,user.getUserName());
//        queryWrapper.eq(StringUtils.hasText(user.getStatus()),User::getStatus,user.getStatus());
//        queryWrapper.eq(StringUtils.hasText(user.getPhonenumber()),User::getPhonenumber,user.getPhonenumber());
//
//        Page<User> page = new Page<>();
//        page.setCurrent(pageNum);
//        page.setSize(pageSize);
//        page(page,queryWrapper);
//
//        //转换成VO
//        List<User> users = page.getRecords();
//        List<UserVo> userVoList = users.stream()
//                .map(u -> BeanCopyUtils.copyBean(u, UserVo.class))
//                .collect(Collectors.toList());
//        PageVo pageVo = new PageVo();
//        pageVo.setTotal(page.getTotal());
//        pageVo.setRows(userVoList);
//        return ResponseResult.okResult(pageVo);
//    }
//
//    @Override
//    public boolean checkUserNameUnique(String userName) {
//        return count(Wrappers.<User>lambdaQuery().eq(User::getUserName,userName))==0;
//    }
//
//    @Override
//    public boolean checkPhoneUnique(User user) {
//        return count(Wrappers.<User>lambdaQuery().eq(User::getPhonenumber,user.getPhonenumber()))==0;
//    }
//
//    @Override
//    public boolean checkEmailUnique(User user) {
//        return count(Wrappers.<User>lambdaQuery().eq(User::getEmail,user.getEmail()))==0;
//    }
//
//    @Override
//    @Transactional
//    public ResponseResult addUser(User user) {
//        //密码加密处理
//        user.setPassword(passwordEncoder.encode(user.getPassword()));
//        save(user);
//
//        if(user.getRoleIds()!=null&&user.getRoleIds().length>0){
//            insertUserRole(user);
//        }
//        return ResponseResult.okResult();
//    }
//
//    @Override
//    @Transactional
//    public void updateUser(User user) {
//        // 删除用户与角色关联
//        LambdaQueryWrapper<UserRole> userRoleUpdateWrapper = new LambdaQueryWrapper<>();
//        userRoleUpdateWrapper.eq(UserRole::getUserId,user.getId());
//        userRoleService.remove(userRoleUpdateWrapper);
//
//        // 新增用户与角色管理
//        insertUserRole(user);
//        // 更新用户信息
//        updateById(user);
//    }
//
//    @Autowired
//    private UserRoleService userRoleService;
//
//    private void insertUserRole(User user) {
//        List<UserRole> sysUserRoles = Arrays.stream(user.getRoleIds())
//                .map(roleId -> new UserRole(user.getId(), roleId)).collect(Collectors.toList());
//        userRoleService.saveBatch(sysUserRoles);
//    }
//
//    private boolean nickNameExist(String nickName) {
//        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(User::getNickName,nickName);
//        return count(queryWrapper)>0;
//    }
//
//    private boolean userNameExist(String userName) {
//        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(User::getUserName,userName);
//        return count(queryWrapper)>0;
//    }
}

